import React, {
  useState,
  useEffect,
  useMemo
} from 'react';
import dayjs from 'dayjs';
import { Toast, Typography, Image, Button, Popconfirm } from '@douyinfe/semi-ui';
import { IconEdit, IconDelete } from '@douyinfe/semi-icons';
import { ColumnProps } from '@douyinfe/semi-ui/lib/es/table';
import {
  getFieldsGoodsList,
  getFieldsGoodsDetail,
  addFieldsGoodsDetail,
  editFieldsGoodsDetail,
  deleteFieldsGoodsDetail,
} from '@/services';
import { useFieldList } from '@/store';
import { EllipseRender } from '@/components';
import type {
  CurrentRowHookOptions,
  FieldsGoodsItem,
  FieldsGoodsListOptions,
  TableColumnsOptions,
  TableFieldsGoodsItem
} from './types';

const { Paragraph } = Typography;

export function useFieldsGoodsList(options: Partial<FieldsGoodsListOptions> = {}) {
  const [page, setPage] = useState(options.page ?? 1);
  const [pageSize, setPageSize] = useState(options.pageSize ?? 10);
  const [keyword, setKeyword] = useState(options.keyword ?? '');
  const [total, setTotal] = useState(0);
  const [tableData, setTableData] = useState<TableFieldsGoodsItem[]>([]);
  const [tableLoading, setTableLoading] = useState(false);

  async function getList(
    page: number,
    pageSize: number,
    keyword: string
  ) {
    setTableLoading(true);
    try {
      const { code, message, data } = await getFieldsGoodsList(page, pageSize, keyword);
      if (code !== 0) {
        throw new Error(message);
      } else {
        const { list, total } = data;
        setTableData(list);
        setTotal(total);
      }
    } catch (e) {
      Toast.error(`${e instanceof Error ? e.message : '请求列表失败'}`);
    }
    setTableLoading(false);
  }

  async function refresh() {
    getList(page, pageSize, keyword);
  }

  const handleKeywordInputChange = (newKeyword: string) => {
    setKeyword(newKeyword);
  }

  const handlePaginationChange = (page: number, pageSize: number) => {
    setPage(page);
    setPageSize(pageSize);
    getList(page, pageSize, keyword);
  }

  useEffect(() => {
    getList(page, pageSize, keyword);
  }, []);

  return {
    page,
    pageSize,
    total,
    keyword,

    tableData,
    tableLoading,

    getList,
    refresh,
    setPage,
    setTableLoading,
    handleKeywordInputChange,
    handlePaginationChange,
  };
}

export function useCurrentRow({
  refresh,
  setLoading,
}: CurrentRowHookOptions) {
  const [currentRow, setCurrentRow] = useState<Partial<FieldsGoodsItem>>({});
  const [modalLoading, setModalLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalType, setModalType] = useState<'create' | 'detail' | 'edit'>('detail');

  function handleCreateClick() {
    setModalType('create');
    setCurrentRow({});
    setModalVisible(true);
  }

  async function handleItemNameClick(row: TableFieldsGoodsItem) {
    setModalType('detail');
    setModalVisible(true);

    try {
      setModalLoading(true);

      const { code, message, data } = await getFieldsGoodsDetail(row.id);
      if (code !== 0) {
        throw new Error(`获取详情内容失败：${message}`);
      }
      setCurrentRow(data);
    } catch (e) {
      Toast.error(`${e instanceof Error ? e.message : '获取详情内容失败'}`);
    }
    setModalLoading(false);
  }

  async function handleEditClick(row: TableFieldsGoodsItem) {
    setModalType('edit');
    setModalVisible(true);

    try {
      setModalLoading(true);

      const { code, message, data } = await getFieldsGoodsDetail(row.id);
      if (code !== 0) {
        throw new Error(`获取详情内容失败：${message}`);
      }
      setCurrentRow(data);
    } catch (e) {
      Toast.error(`${e instanceof Error ? e.message : '获取详情内容失败'}`);
    }
    setModalLoading(false);
  }

  function handleCloseModal() {
    setModalVisible(false);
    setCurrentRow({});
  }

  async function handleAddSubmit(formValue: Partial<FieldsGoodsItem>) {
    try {
      const { code, message } = await addFieldsGoodsDetail(formValue);

      if (code !== 0) {
        throw new Error(`添加失败: ${message}`);
      }
      Toast.success('添加成功');
      handleCloseModal();
      refresh();
    } catch (e) {
      Toast.error(`${e instanceof Error ? e.message : '添加失败'}`);
    }
  }

  async function handleEditSubmit(id: string | number, formValue: Partial<FieldsGoodsItem>) {
    try {
      const { code, message } = await editFieldsGoodsDetail(id, formValue);

      if (code !== 0) {
        throw new Error(`编辑失败: ${message}`);
      }
      Toast.success('编辑成功');
      handleCloseModal();
      refresh();
    } catch (e) {
      Toast.error(`${e instanceof Error ? e.message : '编辑失败'}`);
    }
  }

  async function handleDeleteClick(row: Partial<FieldsGoodsItem>) {
    setLoading(true);
    try {
      const { id } = row;
      const { code, message } = await deleteFieldsGoodsDetail(id);
      if (code !== 0) {
        throw new Error(`删除失败: ${message}`);
      }
      Toast.success('删除成功');
      refresh();
    } catch (e) {
      Toast.error(`${e instanceof Error ? e.message : '删除失败'}`);
    }
    setLoading(false);
  }

  return {
    currentRow,
    modalLoading,
    modalVisible,
    modalType,

    handleItemNameClick,
    handleCreateClick,
    handleEditClick,
    handleDeleteClick,
    handleAddSubmit,
    handleEditSubmit,
    handleCloseModal,
  };
}

export function useTableColumns({
  handleItemNameClick,
  handleEditClick,
  handleDeleteClick,
}: TableColumnsOptions) {
  const fieldList = useFieldList();

  const tableColumns: ColumnProps<TableFieldsGoodsItem>[] = useMemo(() => {
    return [
      {
        title: '名称',
        dataIndex: 'name',
        width: 250,
        fixed: 'left',
        render: (t, row) => (
          <Paragraph>
            <a onClick={() => handleItemNameClick(row)}>{t}</a>
          </Paragraph>
        )
      },
      {
        title: '类型',
        dataIndex: 'field',
        width: 100,
        render: t => (
          fieldList.find(item => item.key === t)?.name ?? t ?? '-'
        )
      },
      {
        title: '封面图片',
        dataIndex: 'img',
        width: 300,
        render: (t: string, row: TableFieldsGoodsItem) => {
          if (!t?.length) return '-';
          return <Image width={200} height={100} src={t} alt={row.name} />
        }
      },
      {
        title: '最低价格',
        dataIndex: 'defaultPrice',
        width: 120,
      },
      {
        title: '价格',
        dataIndex: 'price',
        width: 120,
      },
      {
        title: '地址',
        dataIndex: 'address',
        width: 250,
        render: (t: string) => <EllipseRender message={t} />
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 180,
        render: t => {
          if (!t) return '-';

          return dayjs(t).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        width: 180,
        render: t => {
          if (!t) return '-';

          return dayjs(t).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      {
        title: '操作',
        dataIndex: 'action',
        fixed: 'right',
        width: 200,
        render: (t, row) => (
          <div className="action-group">
            <Button
              className="op-btn"
              type="secondary"
              icon={<IconEdit />}
              aria-label="编辑"
              onClick={() => handleEditClick(row)}
            />
            <Popconfirm
              trigger="click"
              title="确定删除吗？"
              content="刪除后，您可以在回收站找回。"
              showCloseIcon={false}
              onConfirm={() => handleDeleteClick(row)}
            >
              <Button
                className="op-btn"
                type="danger"
                icon={<IconDelete />}
                aria-label="删除"
              />
            </Popconfirm>
          </div>
        ),
      },
    ];
  }, [handleItemNameClick, handleEditClick, handleDeleteClick]);

  return tableColumns;
}
